﻿using System;
using System.Diagnostics;
using System.IO;
//using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Library.Bll;
using Library.Common;
using System.Web;
//using System.Web.UI;
//using System.Web.UI.WebControls;
using Microsoft.VisualBasic;
using System.Collections;
using System.Net;
using System.Xml;
using System.Data;
using System.Net.Mail;
using System.Configuration;
using System.Threading;


namespace HanhuaMicroCredit.BLL
{
    /// <summary>
    /// 订单短信和邮件管理
    /// </summary>
    public class OrderNotice
    {

        public string Title;
        public string noticeType;
        public string busiType;//业务类型
        public string sender;//发送者
        public string orderid;//订单id
        //
        public string mobileEmail;
        public string mContent;
        public static string EMAIL_SENDER_SMTP = (ConfigurationManager.AppSettings["EmailSenderSmtp"] != null && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["EmailSenderSmtp"].ToString()))
            ? ConfigurationManager.AppSettings["EmailSenderSmtp"].ToString() : "smtp.126.com";
        public static int EMAIL_SENDER_PORT = (ConfigurationManager.AppSettings["EmailSenderPort"] != null && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["EmailSenderPort"].ToString()))
            ? Convert.ToInt32(ConfigurationManager.AppSettings["EmailSenderPort"].ToString()) : 25;
        public static string EMAIL_SENDER_ACCOUNT = (ConfigurationManager.AppSettings["EmailSenderAccount"] != null && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["EmailSenderAccount"].ToString()))
                    ? ConfigurationManager.AppSettings["EmailSenderAccount"].ToString() : "hanhuatong@126.com";
        public static string EMAIL_SENDER_PASSWORD = (ConfigurationManager.AppSettings["EmailSenderPassword"] != null && !string.IsNullOrEmpty(ConfigurationManager.AppSettings["EmailSenderPassword"].ToString()))
                    ? ConfigurationManager.AppSettings["EmailSenderPassword"].ToString() : "tonghanhua";

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email">邮件地址</param>
        /// <param name="body">正文 支持html</param>
        /// <param name="title">标题</param>
        /// <param name="data">扩展参数，可不传</param>
        /// <returns></returns>
        public static bool sendEmail(string email, string body, string title, params string[] data)
        {
            try
            {
                bool isEmail = Regex.IsMatch(email, @"^[\w\.]+([-]\w+)*@[A-Za-z0-9-_]+[\.][A-Za-z0-9-_]");
                if (!isEmail)
                    return false;
                OrderNotice send = new OrderNotice();
                send.mobileEmail = email;
                send.mContent = body;
                send.Title = title;
                if (data != null && data.Length > 0)
                {
                    send.busiType = data[0];
                    send.sender = data[1];
                    send.orderid = data[2];
                }
                //send.send(email, body, title);
                Thread Send_Mail = new Thread(new ThreadStart(send.sendEmail));
                Send_Mail.Start();
                return true;


            }
            catch (Exception ee)
            {
                InsLogBll.InsertLog("", "邮件发送", "报错", ee.ToString()); //返回0执行正常，1执行失败

            }
            return false;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">邮件地址</param>
        /// <param name="content">正文</param>
        /// <param name="data">扩展参数，可不传</param>
        /// <returns></returns>
        public static int sendSms(string mobile, string content, params string[] data)
        {
            //新线程取不到
            string s = HttpContext.Current.User.Identity.Name;
            if (string.IsNullOrEmpty(mobile))
                return 0;
            OrderNotice send = new OrderNotice();
            send.mobileEmail = mobile;
            send.mContent = content.Replace(" ", "").Replace("<br/>", "").Replace("&nbsp;", "").Replace("<strong>", "").Replace("</strong>", "");
            if (data != null && data.Length > 0)
            {
                send.busiType = data[0];
                send.sender = data[1];
                send.orderid = data[2];
                send.Title = data[3];
            }
            try
            {
                string status = send.sendSms1();

                //插入数据库记录
                Dictionary<string, object> nextDic = new Dictionary<string, object>();
                nextDic.Add("noticeType", 3);
                nextDic.Add("MTelOrEmail", mobile);
                nextDic.Add("noticeContent", content);

                nextDic.Add("ontime", DateTime.Now.ToString());
                nextDic.Add("status", status);

                int i = CommonBLL.Add("Order_NoticeLog", nextDic);
                InsLogBll.InsertLog("", "sms", "内容", i.ToString() + "|" + mobile + "|" + content); //返回0执行正常，1执行失败

                //Thread Send_Mail = new Thread(new ThreadStart(send.sendSms));
                //Send_Mail.Start();
                return Convert.ToInt32(status);
            }
            catch (Exception ee)
            {
                InsLogBll.InsertLog("", "sms", "发短信异常，内容：", ee.ToString()); //返回0执行正常，1执行失败

            }
            return 0;
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="mobile">邮件地址</param>
        /// <param name="content">正文</param>
        /// <param name="userName">用户名</param>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="data">扩展参数，可不传</param>
        /// <returns></returns>
        public static int sendSms(string mobile, string content, int userId, long loginId, string userName, string ipAddress, params string[] data)
        {
            if (string.IsNullOrEmpty(mobile))
            {
                return 0;
            }

            OrderNotice send = new OrderNotice();
            send.mobileEmail = mobile;
            send.mContent = content.Replace(" ", "").Replace("<br/>", "").Replace("&nbsp;", "").Replace("<strong>", "").Replace("</strong>", "");
            if (data != null && data.Length > 0)
            {
                send.busiType = data[0];
                send.sender = data[1];
                send.orderid = data[2];
                send.Title = data[3];
            }
            try
            {
                string status = send.sendSms1();

                //插入数据库记录
                Dictionary<string, object> nextDic = new Dictionary<string, object>();
                nextDic.Add("noticeType", 3);
                nextDic.Add("MTelOrEmail", mobile);
                nextDic.Add("noticeContent", content);

                nextDic.Add("ontime", DateTime.Now.ToString());
                nextDic.Add("status", status);

                int i = CommonBLL.Add("Order_NoticeLog", nextDic, userId, loginId);
                InsLogBll.InsertLog(userName, "sms", "内容", i.ToString() + "|" + mobile + "|" + content); //返回0执行正常，1执行失败

                return Convert.ToInt32(status);
            }
            catch (Exception ee)
            {
                InsLogBll.InsertLog(userName, "sms", "内容", ee.ToString() + "|" + ipAddress); //返回0执行正常，1执行失败
            }

            return 0;
        }
        /// <summary>
        /// 定时发短信
        /// </summary>
        /// <param name="mov">手机号，可逗号隔开</param>
        /// <param name="content">短信内容</param>
        /// <returns></returns>
        public static string InsertDBSms(string mov, string content)
        {
            string sql = "insert into sms_send(mov,content,priority,sendstate) values(@mov,@content,1,0)";
            ParameterInfo[] parameters = new ParameterInfo[] {
                new ParameterInfo("mov", DbType.String, mov),
                new ParameterInfo("content", DbType.String, content),          
            };
            return CommonBLL.ExecuteSQL4NonQuery(sql, parameters).ToString();
        }

        public static string getVal(object obj)
        {
            if (obj != null)
                return Convert.ToString(obj);
            else
                return "";
        }

        private void sendEmail()
        {
            send(mobileEmail, mContent, Title);
        }

        public static bool send(string to, string body, string title)
        {
            try
            {
                /*
                MailWebService mailService = new MailWebService();
                EaseyeReturnDTO easeyeReturnDTO = mailService.SendMailListRequest(GetEaseyeUserAccountDTO(), GetEaseyeMessageTemplateDTO(title, body), GetEaseyeMessageReceiveDTOList(to).ToArray(), GetEaseyeSendOptionDTO());
                string error = easeyeReturnDTO.ErrorInfo;
                string queryid = easeyeReturnDTO.QueryId;
                 */
                MailMessage message = new MailMessage();
                if (title == "")
                    title = "瀚华通";
                string[] mailParams = Utility.Utils.getConfig("mailSmtp").Split(':');
                message.From = new MailAddress(EMAIL_SENDER_ACCOUNT, "瀚华通");
                string[] toList = to.Split(',');
                foreach (string t in toList)
                {
                    message.To.Add(new MailAddress(t)); // the email you want to send email to 
                }
                message.Subject = title;

                message.IsBodyHtml = true;
                message.BodyEncoding = System.Text.Encoding.UTF8;
                message.Body = body;
                message.Priority = MailPriority.High;

                //SmtpClient client = new SmtpClient(mailParams[0], int.Parse(mailParams[1])); // 587;//Gmail使用的端口 
                //mailParams = Yeex.Web.BLL.Utility.Utils.getConfig("mailAccount").Split(':');
                //client.Credentials = new System.Net.NetworkCredential(mailParams[0], mailParams[1]); // Your user name & password 

                SmtpClient client = new SmtpClient(EMAIL_SENDER_SMTP, EMAIL_SENDER_PORT); // smtp.easeye.com.cn:25 
                client.Credentials = new System.Net.NetworkCredential(EMAIL_SENDER_ACCOUNT, EMAIL_SENDER_PASSWORD); // Your user name & password 
                client.EnableSsl = false; //经过ssl加密 

                client.Send(message);
                return true;
            }
            catch (Exception e)
            {

                InsLogBll.InsertLog("", "Email", "内容", e.ToString()); //返回0执行正常，1执行失败

                return false;
            }



        }

        public string smstest()
        {
            string info = string.Empty, s = string.Empty;
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smsKey"]))
            {
                info += "appSettings[smsKey] is null;";
            }
            else
            {
                s += ConfigurationManager.AppSettings["smsKey"] + "; ";
            }
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smsPwd"]))
            {
                info += "appSettings[smsPwd] is null;";
            }
            else
            {
                s += ConfigurationManager.AppSettings["smsPwd"] + "; ";
            }
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smsServiceNumber"]))
            {
                info += "appSettings[smsServiceNumber] is null;";
            }
            else
            {
                s += ConfigurationManager.AppSettings["smsServiceNumber"] + "; ";
            }
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["smsK"]))
            {
                info += "appSettings[smsK] is null;";
            }
            else
            {
                s += ConfigurationManager.AppSettings["smsK"] + "; ";
            }
            //s = new EncryptionDecryption().encode(s);
            //InsLogBll.InsertLog("", "OrderNotice", "smstest", s);
            return info;
        }

        public int Reg()
        {
            try
            {
                int status = Sms.reg(ConfigurationManager.AppSettings["smsKey"].ToString()
                    , ConfigurationManager.AppSettings["smsPwd"].ToString(), "瀚华通");
                InsLogBll.InsertLog("", "OrderNotice", "smsReg-return-status", status.ToString());
                return status;
            }
            catch (Exception e)
            {
                InsLogBll.InsertLog("", "OrderNotice", "smsReg", e.Message);
                return 9999;
            }
        }

        public int UnReg()
        {
            try
            {
                return Sms.unreg(ConfigurationManager.AppSettings["smsKey"].ToString());
            }
            catch (Exception e)
            {
                InsLogBll.InsertLog("", "OrderNotice", "smsUnReg", e.Message);
                return 9999;
            }
        }

        public int GetBalance(out string balance)
        {
            try
            {
                return Sms.getBalance(ConfigurationManager.AppSettings["smsKey"].ToString(), out balance);
            }
            catch (Exception e)
            {
                balance = "0";
                InsLogBll.InsertLog("", "OrderNotice", "smsGetBalance", e.Message);
                return 9999;
            }
        }

        public string sendSms1()
        {
            string smsKey = ConfigurationManager.AppSettings["smsKey"].ToString();
            //即时发送===这里是软件序列号/手机号/短信内容/优先级
            object[] data = new object[] { smsKey, mobileEmail, mContent, 5 };

            string rec = Sms.setkey(ConfigurationManager.AppSettings["smsK"].ToString()).ToString();
            int r = Sms.send(data);
            rec += "|" + r;
            InsLogBll.InsertLog("", "sendSms1", "内容", rec.ToString()); //返回0执行正常，1执行失败
            return r.ToString();
        }


        public static void SendEmailAndSMS(string phone, string email, Dictionary<string, string> replaces)
        {
            if (!string.IsNullOrEmpty(phone))
            {
                string content = GetTemplateContent("sms_order_success");
                if (!string.IsNullOrEmpty(content))
                {
                    OrderNotice.sendSms(phone, ReplaceTemplate(content, replaces));
                }
            }

            if (!string.IsNullOrEmpty(email))
            {
                string content = GetTemplateContent("email_Order_success");
                if (!string.IsNullOrEmpty(content))
                {
                    OrderNotice.sendEmail(email, ReplaceTemplate(content, replaces), string.Format("瀚华通—— {0} 订单已提交成功", replaces["$lineName"]));
                }
            }
        }

        private static string ReplaceTemplate(string content, Dictionary<string, string> replaces)
        {
            if (replaces == null)
            {
                return content;
            }

            StringBuilder s = new StringBuilder(content);
            foreach (string key in replaces.Keys)
            {
                s.Replace(key, replaces[key]);
            }

            return s.ToString();
        }

        private static string GetTemplateContent(string keyName)
        {
            string sql = "SELECT Template FROM Sys_Template WHERE KeyName=@KeyName";

            Library.Common.ParameterInfo p = new Library.Common.ParameterInfo("KeyName", DbType.String, keyName);

            object t = CommonBLL.ExecuteSQL4Scalar(sql, p);

            if ((t == null) || (t == DBNull.Value))
            {
                return null;
            }

            return t.ToString();
        }

        public interface IBindesh
        {
            string encode(string str);
            string decode(string str);
        }


        public class EncryptionDecryption : IBindesh
        {
            public string encode(string str)
            {
                string htext = "";

                for (int i = 0; i < str.Length; i++)
                {
                    htext = htext + (char)(str[i] + 10 - 1 * 2);
                }
                return htext;
            }

            public string decode(string str)
            {
                string dtext = "";

                for (int i = 0; i < str.Length; i++)
                {
                    dtext = dtext + (char)(str[i] - 10 + 1 * 2);
                }
                return dtext;
            }
        }
    }
}